package cn.tedu.service.impl;

import cn.tedu.mapper.UserMapper;
import cn.tedu.pojo.User;
import cn.tedu.service.UserService;
import cn.tedu.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public String selectUserByUP(User user) {
        byte[] bytes = user.getPassword().getBytes();
        String s = DigestUtils.md5DigestAsHex(bytes);
        user.setPassword(s);
        User user1 = userMapper.selectUserByUP(user);
        if(user == null){
            return null;
        }
        return UUID.randomUUID().toString().replace("-", "");
    }
/*
*  select * from user limit 起始位置,查询条数
* 每页五条
* 第一页：select * from user limit 0,5; 从0开始，取五条,0-4
* 第二页：select * from user limit 5,5；从5开始，取五条，5-9
* 第N页：select * from user limit （页数-1）*条数，条数
 * */
    @Override
    public PageResult getUserListByPage(PageResult pageResult) {
        long total = userMapper.findTotal();
        int size = pageResult.getPageSize();
        int start = (pageResult.getPageNum() - 1) * size;
        String query = pageResult.getQuery();
        List<User> userList = userMapper.findUserByPage(start,size,query);
        return pageResult.setTotal(total).setRows(userList);
    }

    @Override
    @Transactional
    public void updateStatusById(User user) {
        userMapper.updateStatusById(user);
    }

    @Override
    @Transactional
    public void addUser(User user) {
        String password = user.getPassword();
        String md5Pass = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(password).setStatus(true);
        userMapper.addUser(user);
    }

    @Override
    public User findUserById(Integer id) {
        return userMapper.findUserById(id);
    }

    @Override
    @Transactional
    public void updateUserById(User user) {
        userMapper.updateUserById(user);
    }

    @Override
    @Transactional
    public void deleteUserById(Integer id) {
        userMapper.deleteUserById(id);
    }
}
